package com.ckm.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class FindObjectUtil {

    /**
     * 生成查询器map集合
     * @param object 查询类
     * @return map集合
     */
    public static Map<String,Map<Class<?>,Object>> queryWrapper(Object object) {

        HashMap<String,Map<Class<?>,Object>> map = new HashMap<>();
        if (object == null) {
            return map;
        }
        Class<?> aClass = object.getClass();
        for (Field field : aClass.getDeclaredFields()) {
            try {
                if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                    continue;
                }
                Object invoke = FieldUtils.readDeclaredField(object, field.getName(),Boolean.TRUE);
                if (invoke != null) {
                    Map<Class<?>, Object> hashMap = new HashMap<>();
                    hashMap.put(field.getType(), invoke);
                    map.put(field.getName(), hashMap);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }

    /**
     * 填充查询器
     * @param object 查询的类
     * @param wrapper 查询器
     */
    public static void fullQueryWrapper(Object object, QueryWrapper<?> wrapper) {
        for (Map.Entry<String, Map<Class<?>, Object>> entry : queryWrapper(object).entrySet()) {
            for (Map.Entry<Class<?>, Object> objectEntry : entry.getValue().entrySet()) {
                if (objectEntry.getKey().equals(String.class)){
                    wrapper.like(reverseHump(entry.getKey()), objectEntry.getValue());
                }else {
                    wrapper.eq(reverseHump(entry.getKey()), objectEntry.getValue());
                }
            }
        }
    }

    /**
     * 逆驼峰
     * @param str 待处理字符串
     * @return 处理后字符串
     */
    private static String reverseHump(String str) {
        if (str == null || str.trim().isEmpty()) {
            return "";
        }
        StringBuilder stringBuffer = new StringBuilder(str.length());
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                stringBuffer.append("_");
                stringBuffer.append(Character.toLowerCase(c));
            }else {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }
}
